import { login, getUserInfo, getUserDetails } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router/index'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    setToken(data)
    state.token = data
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, data) {
    state.userInfo = { ...data }
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 获取token
  async myLogin(store, data) {
    const res = await login(data)
    localStorage.setItem('time', Date.now())
    store.commit('setToken', res)
  },
  // 获取用户信息
  async getUserInfo(store, data) {
    const res = await getUserInfo()
    // 信息补充
    const detalis = await getUserDetails(res.userId)
    store.commit('setUserInfo', { ...res, ...detalis })
  },
  // 登录退出
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
    resetRouter()
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
